package com.mrx.xfriendship.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.mrx.xfriendship.filter.JWTFilter;
import org.springframework.boot.autoconfigure.jackson.JacksonProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @author : 肖康宁
 * @since : 2022-12-08 14:31
 **/
@Configuration
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http, JWTFilter JWTFilter) throws Exception {
        return http
                // 禁用 csrf
                .csrf().disable()
                // 禁用 session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                // 设置 路由保护规则
                .authorizeRequests()
                // 开放路由
                .antMatchers(
                        "/error", "/captcha", "/user/detail", "/post/index",
                        "/user/login", "/user/logout", "/user/register", "/post/list",
                        "/post/tags", "/post/detail", "/user/postList", "/user/loginBy2faCode",
                        "/chat", "/test", "/test2", "/mail/confirm", "/mail/recovery",
                        "/mail/recoveryConfirm", "/post/tagInfo"
                ).permitAll()
                .antMatchers("/admin/**")
                .hasAuthority("ADMIN")
                // 其它所有路由全部受保护
                .anyRequest().authenticated()
                .and()
                // 添加 jwt 过滤器
                .addFilterBefore(JWTFilter, UsernamePasswordAuthenticationFilter.class)
                .build();
    }

    /**
     * 跨域配置
     */
    @Bean
    public FilterRegistrationBean<CorsFilter> corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(false);
        config.addAllowedOrigin("*");
        config.setAllowedMethods(List.of("*"));
        config.setAllowedHeaders(List.of("*"));
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new CorsFilter(source));
        bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
        return bean;
    }

    /**
     * 设置一个没用的 UserDetailService, 项目里并不会使用, 只是为了抑制警告
     */
    @Bean
    public UserDetailsService userDetailsService() {
        return username -> null;
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * jackson LocalDateTime 格式化配置
     *
     * @param properties 由 SpringBoot 注入 SpringBoot 配置文件里的配置
     */
    @Bean
    public ObjectMapper serializingObjectMapper(JacksonProperties properties) {
        JavaTimeModule module = new JavaTimeModule();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(properties.getDateFormat());
        module.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(formatter));
        module.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(formatter));
        return Jackson2ObjectMapperBuilder.json().modules(module)
                .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS).build();
    }

}
